package com.hook.hookonclick

import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.core.view.get
import java.util.*

object Init {
    lateinit var context: Application

    fun init(context: Application) {
        this.context = context
        registerLifeCircle()
    }

    /**
     * 注册监听所有activity的生命周期
     * 注册fragment的监听
     * getSupportFragmentManager().registerFragmentLifecycleCallbacks(mFragmentLifecycleCallbacks,true);
     */
    private fun registerLifeCircle() {
        context.registerActivityLifecycleCallbacks(object :
            Application.ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
                Log.d("生命周期", "onActivityCreated")
            }

            override fun onActivityStarted(activity: Activity) {
                Log.d("生命周期", "onActivityStarted")
                hookViewWithOnClick(activity)
            }

            override fun onActivityResumed(activity: Activity) {
                Log.d("生命周期", "onActivityResumed")
            }

            override fun onActivityPaused(activity: Activity) {
                Log.d("生命周期", "onActivityPaused")
            }

            override fun onActivityStopped(activity: Activity) {
                Log.d("生命周期", "onActivityStopped")
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
                Log.d("生命周期", "onActivitySaveInstanceState")
            }

            override fun onActivityDestroyed(activity: Activity) {
                Log.d("生命周期", "onActivityDestroyed")
            }
        })
    }

    /**
     * hook activity中所有设置了点击事件的view
     */
    private fun hookViewWithOnClick(activity: Activity) {
        val contentView = activity.findViewById<View>(android.R.id.content)
        viewForEach(contentView)
    }

    private fun viewForEach(view: View) {
//        if (view is ViewGroup) {
//            for (i in 0 until view.childCount) {
//                viewForEach(view[i])
//            }
//        } else {
//            HookOnClick.hookOnClickListener(view)
//        }
        //不使用递归遍历
        val list = LinkedList<ViewGroup>()
        if (view is ViewGroup) {
            list.add(view)
        }

        while (list.isNotEmpty()) {
            val viewGroup = list.removeFirst()
            //viewGroup也有可能设置点击事件
            HookOnClick.hookOnClickListener(viewGroup)

            for (i in 0 until viewGroup.childCount) {
                val childView = viewGroup[i]

                if (childView is ViewGroup) {
                    list.add(childView)
                } else {
                    HookOnClick.hookOnClickListener(childView)
                }
            }
        }
    }
}